<script setup>
import {ref,getCurrentInstance} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import QQMapWX from '../../libs/qqmap-wx-jssdk.js'
import {reqAddAddress,reqAddressInfo,reqUpdateAddress} from '../../api/address.js'
// 把经纬度转化为具体位置的对象
const qqmapwx = ref()
let addressId = ref()
onLoad(async(options)=>{
	qqmapwx.value = new QQMapWX({
		key:'UAIBZ-OLWEB-X4FUN-NZC7F-5GJTT-7GBL3'
	})
	addressId.value = options.id
	// 如果是更新地址信息就调用此方法对地址进行初始化
	showAddressInfo(options.id)	
})
const showAddressInfo = async(addressId)=>{
	if(addressId){
		uni.setNavigationBarTitle({title:'更新收货地址'})
		const res = await reqAddressInfo(addressId)
		Object.assign(address.value,res.data)
		const {provinceName,cityName,districtName} = address.value
		showAddress.value = provinceName+" "+cityName+" "+districtName
		// console.log(res);
	}
}
const {proxy} = getCurrentInstance()
// 对表格的引用
const baseForm = ref()
// 地址对象
const address = ref({
	name: "",//收货人
	phone: "",//手机号码
	provinceName: "",//省
	provinceCode: "",//省编码
	cityName: "",//市
	cityCode: "",//市编码
	districtName: "",//区
	districtCode: "",//市编码
	address: "",//详细地址
	fullAddress: "",//完整地址
	isDefault: false//是否设置为默认地址
})
const styles = ref({
	borderColor: 'transparent'
})
const showAddress = ref('无地址 请选择')
// 通过picker来选择地址
const bindPickerChange = (e)=>{
	const [provinceCode,cityCode,districtCode] = e.detail.code
	const [provinceName,cityName,districtName] = e.detail.value
	Object.assign(address.value,{provinceCode,cityCode,districtCode,provinceName,cityName,districtName})
	showAddress.value = e.detail.value.join(' ')
	// console.log(address.value);
}
const nameRegExp = '^[\\u4e00-\\u9fa5]{2,4}$'
const phoneRegExp = '^1[3-9]\\d{9}$'
const rules = {
	name:{
		rules:[
			{required:true,errorMessage:'姓名为必填项'},
			{format:'string',errorMessage:'类型必须为字符串'},
			{pattern:nameRegExp,errorMessage:'长度最少2个字最多3个字'},			
		]
	},
	phone:{
		rules:[
			{required:true,errorMessage:'电话为必填项'},
			{format:'string',errorMessage:'类型必须为字符串'},
			{pattern:phoneRegExp,errorMessage:'请输入正确的手机号'},
		]
	},
	address:{
		rules:[
			{required:true,errorMessage:'详细地址为必填项'},
			{format:'string',errorMessage:'类型必须为字符串'},
		]
	}
}
// 保存所要添加的地址，可以再此进行表单验证
const submit = async(baseForm)=>{
	if(showAddress.value === '无地址 请选择'){
		return proxy.$toast({title:'请选择地区'})
	}
	const params ={
		...address.value,
		fullAddress:showAddress.value.trim()+address.value.address,
		isDefault:address.value.isDefault?1:0
	}
	// console.log(params);
	try{
		// 校验不通过抛出错误，用catch捕获。通过，可以接收输入框内的值
		await baseForm.validate()
		const res = addressId.value?await reqUpdateAddress(params):await reqAddAddress(params)
		if(res.code===200){
			uni.navigateBack()
		}
		// console.log(res);
		proxy.$toast({title:addressId.value?'更新成功！':'添加成功！'})
		// console.log(res);	
	}catch(e){
		// console.log(e);
		proxy.$toast({title:'网络出错了!'})
	}
}
// 通过地图功能来选择地址
const onLocation = async()=>{
	try{
		const {latitude,longitude,name} = await uni.chooseLocation()
		// console.log(latitude,longitude,name);
		qqmapwx.value.reverseGeocoder({
			location:{
				latitude,longitude
			},
			success:(res)=>{
				// console.log(res);
				// 获取省市区编码
				const {adcode,province,city,district} = res.result.ad_info
				// 获取街道、门牌（这两个值可能为空）
				const {street,street_number} = res.result.address_component
				// 获取标准地址
				const {standard_address} = res.result.formatted_addresses	
				// 对获取的数据进行格式化、组织，然后赋值给data中的字段
				//adcode如果是省，前2位有值，后面4位是0
				 //如果是市，前4位有值，后面2位是0				 				
				 address.value.provinceName=province			 
				 address.value.provinceCode=adcode.replace(adcode.substring(2,6),'0000')
				 address.value.cityName=city
				 address.value.cityCode=adcode.replace(adcode.substring(4,6),'00')
				 address.value.districtName=district
				 address.value.districtCode=district&&adcode
				 // 组织详细地址
				 address.value.address=street+street_number+name
				 address.value.fullAddress=standard_address+name
				 showAddress.value=province+' '+city+' '+district
				 // console.log(address.value);
			},
			// fail:(e)=>{
			// 	console.log(e);
			// }
		})
		// console.log(res);
	}catch(e){
		 proxy.$toast({
			 title:"您拒绝授权获取地理位置。"
		 })
	}	
}
/**
 * 暂时无法使用该API，理解逻辑即可
 */
const logic = async()=>{
	const {authSetting} = await uni.getSetting()
	// 判断用户是否拒绝了授权
	if(authSetting['scope.userLocation'] === false){
		// 用户之前拒绝授权获取位置信息，用户再次发起了授权
		// 这个时候需要使用一个弹窗询问用户是否进行授权
		const modalRes = await proxy.$modal({
			title:'授权提示',
			content:'需要获取地理位置信息，请确认授权'
		})
		if(!modalRes) return proxy.$toast({title:'您拒绝了授权'})
		// 点击确定，说明用户同意授权，需要打开微信客户端小程序授权页面
		if(modalRes){
			const {authSetting} = await uni.openSetting()
			if(!authSetting['scope.userLocation']) return proxy.$toast({title:'授权失败'})
			try{
				await uni.getLocation()
				// const res = await uni.getLocation()
				// console.log(res);
			}catch(e){
				proxy.$toast({
					title:"您拒绝授权获取地理位置。"
				})
			}
		}
	}else{
		try{
			await uni.getLocation()
			// const res = await uni.getLocation()
			// console.log(res);
		}catch(e){
			proxy.$toast({
				title:"您拒绝授权获取地理位置。"
			})
		}
	}
}
// 是否开启默认地址
const changeSwitch =(e)=>{
	address.value.isDefault=e.detail.value
}
</script>

<template>
	<view class="add-address">
		<!-- 基础用法，不包含校验规则 -->
		<uni-forms ref="baseForm" 
		:modelValue="address" 
		:border="true" 
		:rules="rules"
		>
			<uni-forms-item label="收货人" name="name" :required='true'> 
				<uni-easyinput v-model="address.name" placeholder="请输入收货人" :styles="styles" :inputBorder="false" primaryColor="#535353"/>
			</uni-forms-item>
			<uni-forms-item label="手机号码" :label-width="80" name="phone" :required='true'> 
				<uni-easyinput v-model="address.phone" placeholder="请输入手机号码" :styles="styles" :inputBorder="false" primaryColor="#535353"/>
			</uni-forms-item>
			<uni-forms-item label="所在地区" :label-width="80" :required='true'>
				<template #default>
					<view class="select-address">
						<picker @change="bindPickerChange"
							mode = region							
							class="address-picker">
							<view class="uni-input">
								{{showAddress}}
							</view>
						</picker>
						<view class="location" @click="onLocation">
							<text class="icon-dingwei iconfont"></text>
							定位
						</view>
					</view>	
				</template>
			</uni-forms-item>
			<uni-forms-item label="详细地址" :label-width="80" name="address" :required='true'>
				<uni-easyinput v-model="address.address" placeholder="详细地址" :styles="styles" :inputBorder="false" primaryColor="#535353"/>
			</uni-forms-item>
			<uni-forms-item label="设置默认地址" :label-width="100" name="isDefault">
				<template #default>
					<view class="default-address">
						<switch  
							color="#f3514f" 
							style="transform: scale(0.8);" 
							@change="changeSwitch" 
							:checked="address.isDefault"
						/>
					</view>
				</template>
			</uni-forms-item>
		</uni-forms>
		<view class="save">
			<button type="warn" class="save-btn" @click="submit(baseForm)">保存</button>
		</view>
	</view>
</template>

<style lang="scss" scoped>
.add-address{
	padding: 20rpx;
	:deep(.uni-forms){
		background: #ffffff;
		padding:0 16rpx;
	}
	.select-address{
		display: flex;
		justify-content: space-between;
		flex-direction: row;
		margin-top: 10rpx;
		.address-picker{
			padding: 10rpx 0;
			width: 80%;
			.uni-input{
				font-size: 24rpx;
				color: #939393;
			}
		}
		.location{
			padding: 10rpx 0;
			display: flex;
			flex-direction: row;
			align-items: center;
			margin-right: 10rpx;
			font-size: 24rpx;
			color:#939393;			
		}
	}
	.default-address{
		display: flex;
		justify-content: flex-end;
	}
	.save{
		text-align: center;
		margin-top: 20rpx;
		.save-btn{
			font-size: 26rpx;
			height: 80rpx;
			width: 500rpx;
			border-radius: 50rpx;
			line-height: 80rpx;
		}
	}
}
</style>
